<template>

  <Select v-model:open="isOpen" :disabled="disabled" @update:modelValue="handleCloseSelect"
    @update:open="handleQueryPrevNodeOutput">
    <SelectTrigger class="w-full" as="div">
      <SelectValue :placeholder="placeholder" />
    </SelectTrigger>
    <SelectContent>
      <SelectGroup>
        <SelectItem class="text-gray-500" v-for="(option, index) in OptionsData" :key="option.value + index"
          :value="option.value">
          {{ option.label }}
        </SelectItem>
      </SelectGroup>
      <!-- <p v-else class="px-2 text-xs text-gray-500 text-muted-foreground">暂无数据</p>
      <SelectSeparator v-if="isTree" class="h-[1px] w-full bg-gray-300" /> -->
      <Navigation v-if="isTree" :data="currentOptionsTree"
        @update:selectedNodePath="(data) => handleSelectedNodePath(data)" />
    </SelectContent>
  </Select>
</template>

<script lang="ts">
import { defineComponent, ref, watch, nextTick, toRaw, onMounted } from 'vue'
import { TreeItem, TreeRoot } from 'radix-vue'
import { Icon } from '@iconify/vue'
import { cloneDeep, isArray } from 'lodash'
import Navigation from '../navigation.vue'
import storeMap from '@/pina'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
  SelectSeparator,
  SelectLabel
} from '@/components/ui/select'
import { useVueFlow, useNode } from '@vue-flow/core'
import type { SelectRootEmits, SelectRootProps } from 'radix-vue'
import { SelectRoot, useForwardPropsEmits } from 'radix-vue'
import { findConnectedNodes } from '@/lib/utils'

// interface Ioptions {
//     label: String,
//     value: String
// }
// interface Iporps{
//     disabled: Boolean,
//     Options: Ioptions[]  // 定义 Options 类型为 IOptions[] 数组，并要求必填
// }
export default defineComponent({
  components: {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectTrigger,
    SelectValue,
    SelectSeparator,
    SelectLabel,
    TreeRoot,
    TreeItem,
    Icon,
    Navigation
  },
  props: {
    disabled: Boolean,
    placeholder: String,
    Options: {
      type: Array || Object,
      required: true,
      default: () => [
        {
          label: String,
          value: String
        }
      ]
    },
    defaultValue: String,
    items: {
      type: Array,
      default: []
    },
    nodeId: String,
    storeId: String,
    isTree: Boolean,
    type: String
  },
  setup(props: any, { emit }) {
    const { getEdges, getNodes, edges } = useVueFlow()
    const { storeId, nodeId, Options, isTree, disabled } = props
    const isOpen = ref(false)
    let currentOptionsTree = ref([])
    const currentNodeId = nodeId;
    const OptionsStore = storeMap.useOptionsStore()
    let OptionsData = ref([])
    const handleSelectedNodePath = (data: any) => {
      OptionsData.value = [data]
      nextTick(() => {
        isOpen.value = false
        emit('update:modelValue', data.value)
      })

    }

    const findValueInTree = (val) => Object.values(props.Options).map((item: any) => item.Options.filter(el => el.label == val)).flat()
    onMounted(() => {
      OptionsData.value = isArray(toRaw(props.Options)) ? props.Options : findValueInTree(props.defaultValue)
    })
    const handleCloseSelect = (val) => {
      isOpen.value = false
    }
    const handleQueryPrevNodeOutput = (flag) => {
      if (flag && isTree) {
        const connectedNodes = [...findConnectedNodes(currentNodeId, getEdges.value, getNodes.value)]
        let selectObj = {}
        connectedNodes.map((item) => {
          if (item.data.output) {
            const istree = item.data.output.some(
              (item: any) => Array.isArray(item.children) && item.children.length > 0
            )
            const SelectOption = {
              groupName: item.data.title,
              // id:`${item.data.title}-${}`,
              Options: istree
                ? item.data.output
                : item.data.output.map((el: any,i:number) => {
                  return {
                    label: el.name,
                    value: el.name,
                    id:`${item.data.title}-${i}`,
                  }
                })
            }
            selectObj[item.data.title] = SelectOption
          }
        })
        storeMap.useOptionsStore().addReferenceOption(selectObj)
        const OptionsStore = storeMap.useOptionsStore()
        const options = OptionsStore.referenceObject
        currentOptionsTree.value = { ...options }
        const linkedNodeId = edges.value
          .filter((edge) => edge.source === nodeId || edge.target === nodeId)
          .find((edge) => (edge.source === nodeId ? edge.target : edge.source))?.source
        linkedNodeId && storeMap[storeId]().updateRef(linkedNodeId)
      }
    }
    watch(() => OptionsStore, (n, o) => {
      if (n && Object.values(n.selectOptions).length&&isTree) {
        const Options = Object.values(n.selectOptions)[0]?.Options
        const groupName = Object.values(n.selectOptions)[0]?.groupName
        const id = Object.values(n.selectOptions)[0]?.id
        const titName = OptionsData.value[0].label.split('-')[0]
        const OptionId =  OptionsData.value[0].id
        console.log(OptionsData,id,OptionId,'OptionsData')
        if(titName == groupName&&id == OptionId){
            OptionsData.value = [
            {
              label:`${groupName}-${Options[0].value}` ,
              value: Options[0].value,
              id
            }
          ]
        }
        
        // item.value = Options[0].value
      }
    }, { deep: true })
    return {
      handleSelectedNodePath,
      // handleTreeToggle,
      // handleSetPath,
      handleQueryPrevNodeOutput,
      OptionsData,
      currentOptionsTree,
      isOpen,
      handleCloseSelect
    }
  }
})
</script>

<style lang="scss" scoped></style>
